#!/bin/bash

#Created by Cheng 2015-1008
#Version 1.0

if [ $# -lt 1 ]; then
	echo `date +"%Y-%m-%d %H:%M:%S"`  "Usage: <DIRNUM> <ROOMNO>"
	exit 1
fi

SOURCEDATAPATH=/ftpdata/bsmp/data
TMPDATAPATH=/ftpdata/bsmp/streamsdata/tmpdata
BUFFDATAPATH=/ftpdata/bsmp/streamsdata/buff
WORKPATH=/ftpdata/bsmp/streamsdata/
DIRNUM=$1
ROOMNO=$2
FILESNAME=*${ROOMNO}*.gz

while true
do

DATE=`date +%Y%m%d`
LOGFILE=${WORKPATH}log/flume_idc_datamv_${ROOMNO}_${DATE}.log

	DATEDIR=`date +%Y%m%d`
        FileNum=`find ${SOURCEDATAPATH}/${DATEDIR}/ -name "*${ROOMNO}*.gz"|wc -l`
#	FileNum=`ls ${SOURCEDATAPATH}/${DATEDIR}/*.gz -lR|grep "^-"|wc -l`
#        DirNum=`expr ${FileNum} / 2`
        echo 'FileNum is '${FileNum} | tee -a ${LOGFILE}
#        echo 'DirNum is '${DIRNUM} | tee -a ${LOGFILE}

     		
      if (( $FileNum > 0 )); then
        echo 'move data from' ${SOURCEDATAPATH} 'to' ${TMPDATAPATH} | tee -a ${LOGFILE}
        mv `find ${SOURCEDATAPATH}/${DATEDIR} -name "${FILESNAME}" | sort -u | head -32` ${TMPDATAPATH}

        echo 'tar file.....' | tee -a ${LOGFILE}
        for tar in ${TMPDATAPATH}/*${ROOMNO}* ;do tar zxvf $tar -C ${BUFFDATAPATH}/ ;done | tee -a ${LOGFILE}

        echo 'remove tmpdata' | tee -a ${LOGFILE}
        rm -rf ${TMPDATAPATH}/*.gz | tee -a ${LOGFILE}
		fi
	
		COUNT=1
        while (( $COUNT<=$DIRNUM ))
        do
                DATAPATH=/ftpdata/bsmp/streamsdata/flumebuff${COUNT}
                if [ ! -d $DATAPATH ]; then
                        mkdir -p $DATAPATH | tee -a ${LOGFILE}
                fi;
    
                echo "move txt from ${BUFFDATAPATH} to /ftpdata/bsmp/streamsdata/flumebuff"$COUNT | tee -a ${LOGFILE}
		TargetFileNum=`ls ${DATAPATH}/*.txt -lR|grep "^-"|wc -l`
		if (( $TargetFileNum < 3 ));
		then
			REMAINNUM=$[ 3 - $TargetFileNum ]
			echo "remain num is ${REMAINNUM}" | tee -a ${LOGFILE}
			if (( $REMAINNUM > 0 ));
			then 
                		#mv `ls ${BUFFDATAPATH}/*${ROOMNO}*|sort -u|head -${REMAINNUM}`  ${DATAPATH} | tee -a ${LOGFILE}
                		mv `find ${BUFFDATAPATH} -name "*${ROOMNO}*.txt" |sort -u|head -3`  ${DATAPATH}
				echo `date +"%Y-%m-%d %H:%M:%S"`  "mv file success ${DATAPATH}"   | tee -a ${LOGFILE}
			fi
		fi
                COUNT=$[COUNT+1]

        done
      
        #       echo 'sleep.....start'
                sleep 3
        #       echo 'sleep....end'
done

